﻿using System;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace SIToFb2
{
  public partial class MainForm : Form
  {
    private readonly MainFormView _mainFormView;

    public MainForm()
    {
      InitializeComponent();
      _mainFormView = new MainFormView();
      _bindingSource.DataSource = _mainFormView;
    }

    public MainForm(string pagePath)
    {
      InitializeComponent();
      _mainFormView = new MainFormView { PagePath = pagePath };
      _bindingSource.DataSource = _mainFormView;
    }

    protected override void OnLoad(EventArgs e)
    {
      base.OnLoad(e);
      _mainFormView.Messages.Notification("Tool started.");
    }

    private void SelectedPageTextChanged(object sender, EventArgs e)
    {
//      var myDocPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
      var selectedFileName = _mainFormView.GetSelectedFileName();
      var resFb2 = Path.GetFileNameWithoutExtension(selectedFileName) + ".fb2";
      var fullPath = Path.Combine(Path.GetDirectoryName(_mainFormView.PagePath), resFb2);
      if (_savePathTextBox.Text != fullPath)
        _mainFormView.SavePath = _savePathTextBox.Text = fullPath;
    }

    private void ChoosePageBtnClick(object sender, EventArgs e)
    {
      using (var ofd = new OpenFileDialog())
        if (ofd.ShowDialog(this) == DialogResult.OK)
          _mainFormView.PagePath = ofd.FileName;
    }

    private void ChooseResBtnClick(object sender, EventArgs e)
    {
      using (var sfd = new SaveFileDialog())
        if (sfd.ShowDialog(this) == DialogResult.OK)
          _mainFormView.SavePath = _savePathTextBox.Text = sfd.FileName;
    }

    private void ShowPageBtnClick(object sender, EventArgs e)
    {
      using (var form = new Form { Size = new Size(800, 600) })
      {
        var webBrowser = new WebBrowser
                           {
                             Dock = DockStyle.Fill,
                             Url = new Uri(_mainFormView.PagePath)
                           };
        form.Controls.Add(webBrowser);
        form.ShowDialog(this);
      }
    }

    private void StartBtnClick(object sender, EventArgs e)
    {
      new Thread(Transform).Start();
    }

    private void Transform()
    {
      _mainFormView.Transform();
    }
  }
}
